package org.apache.struts2.plugin.json.writer;

import java.io.IOException;
import java.io.OutputStream;
import org.apache.struts2.plugin.json.Token;
import org.apache.struts2.plugin.json.model.JSONValue;

/**
 * Definition of an abstract writer of JSON.
 * @author VERDOÏA Laurent <verdoialaurent@gmail.com>
 */
public abstract class AbstractJSONWriter<T extends JSONValue> {

    private Token open;
    private Token close;
    protected T content;
    protected OutputStream out;

    public AbstractJSONWriter(T content, OutputStream out) {
        this(content, out, null, null);
    }

    public AbstractJSONWriter(T content, OutputStream out, Token open,
            Token close) {
        this.content = content;
        this.out = out;
        this.open = open;
        this.close = close;
    }

    public void write() throws IOException {
        if (this.content.isNull() == true) {
            this.out.write(Token.NULL.getBytes());
        } else {
            writeOpen();
            writeContent();
            writeClose();
        }
    }

    protected void writeOpen() throws IOException {
        this.out.write(this.open.getBytes());
    }

    protected void writeClose() throws IOException {
        this.out.write(this.close.getBytes());
    }

    protected abstract void writeContent() throws IOException;
}
